<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../scripts/ext-3.3.1/resources/css/ext-all.css"/>
	<link rel="stylesheet" type="text/css" href="../styles/global.css"/>
	<script type="text/javascript" src="../scripts/ext-3.3.1/adapter/ext/ext-base.js"></script>
	<script type="text/javascript" src="../scripts/ext-3.3.1/ext-all.js"></script>
	<script type="text/javascript" src="../scripts/extjs-plus.js"></script>
<title></title>
<style>
.opt{
	margin-right:5px;
	padding:2px 0px;
}
</style>
<script type="text/javascript">
	Ext.onReady(function(){
		gridpanel = dzcx_load();
	});
	function dzcx_load(){
		var sm = new Ext.grid.CheckboxSelectionModel();
		var options = {
				title:"定制查询",
				cm:new Ext.grid.ColumnModel([
					new Ext.grid.RowNumberer(),
					sm,
					{header:"ID",width:50,sortable:true,dataIndex:"id",id:"id",hidden:true},
					{header:"标题",width:300,sortable:true,dataIndex:"bt",id:"bt"},
					{header:"启用",width:100,sortable:true,dataIndex:"flag",id:"flag",renderer:function(v){return v=='Y'?'启用':'禁用';}},
					{
						xtype:"actioncolumn",
						width:100,
						items:[{
			            	icon:"../scripts/ext-3.3.1/resources/images/default/dd/drop-delete.gif",
							tooltip:"删除",
			            	handler:function(grid,rowIndex,colIndex){
			            		var id = gridpanel.getStore().getAt(rowIndex).get("id");
			            		var ids = [id];
			            		dzcx_delete(ids);
			            	}
						},{
			            	icon:"../scripts/ext-3.3.1/resources/images/default/dd/edit.gif",
							tooltip:"编辑",
			            	handler:function(grid,rowIndex,colIndex){
			            		var id = gridpanel.getStore().getAt(rowIndex).get("id");
			            		edit_show(id);
			            	}
						}]
					}
		        ]),
				record:new Ext.data.Record.create([
	               	{name:"index",type:"int"},
				    {name:"id",type:"id"},
	            	{name:"bt",type:"string"},
	            	{name:"flag",type:"string"}
				]),
	            url:"<s:url action='admin/dzcx_list'/>",
	            start:0,
	            limit:20,
	            sm:sm,
	            autoExpandColumnId:"bt",
	            showBottomBar:true,
	            tbar:[{
	            	text:"添加",
	            	icon:"../scripts/ext-3.3.1/resources/images/default/dd/drop-add.gif",
	            	handler:function(){
	            		dzcx_add();
	            	}
	            },{
	            	text:"删除",
	            	icon:"../scripts/ext-3.3.1/resources/images/default/dd/drop-delete.gif",
	            	handler:function(){
	            		var view = gridpanel.getView();
	            		var store = gridpanel.getStore();
	            		var sm = gridpanel.getSelectionModel();
	            		var ids = [];
	            		for(var i=0;i<view.getRows().length;i++){
	            			if(sm.isSelected(i)){
	            				ids.push(store.getAt(i).get("id"));
	            			}
	            		}
	            		dzcx_delete(ids);
	            	}
	            },{
	            	text:"刷新",
	            	icon:"../scripts/ext-3.3.1/resources/images/default/grid/refresh.gif",
	            	handler:function(){
	    				gridpanel.getStore().reload();
	    			}
	            }]
			};
			
			return create_gridpanel(options).render("list");
	}
	function dzcx_add(dzcx_id,dzcx,dzcx_column){
		var c_record = Ext.data.Record.create([
		                                       {name:"dm",type:"string",mapping:"dm"},
		                                       {name:"mc",type:"string",mapping:"mc"},
		                                       {name:"sjlx",type:"string",mapping:"sjlx"},
		                                       {name:"width",type:"String",mapping:"width"},
		                                       {name:"renderer",type:"string",mapping:"renderer"}
		                                       ]);
		var data = "";
		if(dzcx_id){
			data = dzcx_column;
		}else{
			data = [{dm:"",mc:"",sjlx:"right",width:100,renderer:""}];
		}
		var c_reader = new Ext.data.JsonReader({},c_record);
		var c_proxy = new Ext.data.MemoryProxy(data);
		var c_store = new Ext.data.Store({proxy:c_proxy,reader:c_reader});
		c_store.load();

		var sm = new Ext.grid.CheckboxSelectionModel();
		var c_cm = new Ext.grid.ColumnModel([
		                                     new Ext.grid.RowNumberer(),
		                                     sm,
		                                     {header:"列名",dataIndex:"dm",width:40,
		                                    	 editor:new Ext.grid.GridEditor(new Ext.form.TextField())},
		                                     {header:"列标题",dataIndex:"mc",width:80,
		                                    	 editor:new Ext.grid.GridEditor(new Ext.form.TextField())},
			                                 {header:"对齐",dataIndex:"sjlx",width:60,
		                                    	 editor:new Ext.grid.GridEditor(new Ext.form.TextField())},
			                                 {header:"宽度(px)",dataIndex:"width",width:40,
			                                    	 editor:new Ext.grid.GridEditor(new Ext.form.TextField())},
		                                     {header:"数据渲染（renderer）",dataIndex:"renderer",width:80,id:"renderer",
		                                    	 editor:new Ext.grid.GridEditor(new Ext.form.TextField())}
	                                     	]);
		var c_grid = new Ext.grid.EditorGridPanel({
			store:c_store,
			cm:c_cm,
			sm:sm,
			fieldLabel:"定义列",
			autoExpandColumn:"renderer",
			width:600,
			height:150,
			clicksToEdit:1,
			autoScroll:true,
			autoEncode:true,
			tbar:[{
				text:"添加一行",
            	icon:"../scripts/ext-3.3.1/resources/images/default/dd/drop-add.gif",
            	handler:function(){
            		c_grid.stopEditing();
            		var data_init = [{dm:"",mc:"",sjlx:"right",width:100,renderer:""}];
            		var record_new = new c_record(data_init);
            		c_grid.getStore().add(record_new);
            		record_new.dirty = true;
            		record_new.modified=data_init;
            		if(c_grid.getStore().modified.indexOf(record_new)==-1){
            			c_grid.getStore().modified.push(record_new);
            		}
            	}
			},{
            	text:"删除选定行",
            	icon:"../scripts/ext-3.3.1/resources/images/default/dd/drop-delete.gif",
            	handler:function(){
            		var c_sm = c_grid.getSelectionModel();
            		if(c_sm.hasSelection()){
            			Ext.MessageBox.confirm("确认删除","确定要删除选中的行吗？",function(btn){
            				if(btn=="yes"){
            					for(var i=0;i<c_grid.getView().getRows().length;i++){
        	            			if(c_sm.isSelected(i)){
                    					c_grid.getStore().removeAt(i);
                    					i--;
        	            			}
        	            		}
            					c_grid.getView().refresh();
            				}
            			});
            		}else{
            			Ext.MessageBox.alert("错误","请选择要删除的行!");
            		}
            	}
			}],
			viewConfig:{
				forceFit:true
			}
		});
		var f = new Ext.form.FormPanel({
			labelAlign:"right",
			region:"center",
			frame:true,
			items:[{
				xtype:"textfield",
				name:"bt",
				fieldLabel:"标题",
				width:600,
				value:dzcx?dzcx.bt:""
			},{
				xtype:"textarea",
				name:"sm",
				value:dzcx?dzcx.sm:"",
				fieldLabel:"说明",
				width:600
			},{
				xtype:"textarea",
				name:"sqlcode",
				value:dzcx?dzcx.sqlcode:"",
				fieldLabel:"查询SQL",
				width:600,
				height:150
			},c_grid,{
				xtype:"checkbox",
				fieldLabel:"启用",
				name:"flag",
				checked:(dzcx && dzcx.flag=='N')?false:true,
				value:"Y"
			}],
			buttonAlign:"center",
			buttons:[{
				text:"提交",
				handler:function(){
					var bt = f.getForm().findField("bt").getValue();
					var sm = f.getForm().findField("sm").getValue();
					var sqlcode = f.getForm().findField("sqlcode").getValue();
					var flag = f.getForm().findField("flag").checked?'Y':'N';
					
					if(bt.length==0 || sqlcode.length==0){
						Ext.MessageBox.alert("错误","标题或查询SQL不能为空");
						return false;
					}
					
					/* 列定义 */
					var store = c_grid.getStore();
					var length = c_grid.getView().getRows().length;
					var columns = [];
					for(var i=0;i<length;i++){
						var dm = store.getAt(i).get("dm");
						var mc = store.getAt(i).get("mc");
						var sjlx = store.getAt(i).get("sjlx");
						var width = store.getAt(i).get("width");
						var renderer = store.getAt(i).get("renderer");
						if(mc && mc.length>0){
							columns.push({idx:""+i,dm:dm,mc:mc,sjlx:sjlx,width:""+width,renderer:renderer});
						}
					}
					if(columns.length==0){
						Ext.MessageBox.alert("错误","至少定义一个列");
						return false;
					}
					
					/* 将列定义保存到数据库 */
					var requestoptions = {
						url:"<s:url action='admin/dzcx_add'/>",
						params:{bt:bt,sm:sm,sqlcode:sqlcode,flag:flag,columns:Ext.util.JSON.encode(columns)},
						success:function(response,config){
							if(response.responseText=='1'){
								gridpanel.getStore().reload();
								win.close();
							}else{
								Ext.MessageBox.alert("错误","保存失败，请检查数据!");
							}
						},
						failure:function(response,config){
							Ext.MessageBox.alert("错误","保存失败，请稍候再试!");
						}
					};
					if(dzcx_id){
						requestoptions.url="<s:url action='adin/dzcx_saveedit'/>";
						requestoptions.params.id=dzcx_id;
					}
					Ext.Ajax.request(requestoptions);
				}
			},{
				text:"取消",
				handler:function(){
					win.close();
				}
			}]
		});
		var win = new Ext.Window({
			title:dzcx_id?"编辑定制查询":"添加一个定制查询",
			width:800,
			height:500,
			layout:"border",
			modal:true,
			items:[f]
		});
		win.show();
	}
	function dzcx_delete(ids){
		if(ids.length>0){
			Ext.MessageBox.confirm("删除","确定要删除吗？",function(btn,txt){
				if(btn=='no'){
					return false;
				}
				Ext.Ajax.request({
					url:"<s:url action='admin/dzcx_delete'/>",
					params:{ids:Ext.util.JSON.encode(ids)},
					method:"post",
					success:function(response,config){
						if(response.responseText==1){
							gridpanel.getStore().reload();
						}else{
							Ext.MessageBox.alert("错误","删除失败，请联系管理员!");
						}
					},
					failure:function(response,config){
						Ext.MessageBox.alert("错误","删除失败，请稍候再试!");
					}
				});
			});
		}else{
			Ext.MessageBox.alert("错误","请选择要删除的行!");
		}
	}
	function edit_show(id){
		var mask = new Ext.LoadMask(Ext.getBody(),{msg:"加载中，请稍候。。。"});
		mask.show();
		Ext.Ajax.request({
			url:"<s:url action='admin/dzcx_edit'/>",
			params:{id:id},
			method:"post",
			success:function(response,config){
				mask.hide();
				var json = Ext.util.JSON.decode(Ext.util.JSON.decode(response.responseText,true),true);
				if(json.result!="0"){
					var dzcx = json.dzcx;
					var dzcx_column = json.dzcx_column;
					dzcx_add(id,dzcx,dzcx_column);
				}else{
					Ext.MessageBox.alert("错误","数据加载失败！");
				}
			}
		})
	}
</script>
</head>
<body>
<div id="list"></div>
<div id="add"></div>
</body>
</html>